package com.rabbitmq.work.fair;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

//消费者1
public class Work1 {
    public static void main(String[] args) {
        System.out.println("work1 开始工作");
        //1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.122.113.100");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("123");
        factory.setVirtualHost("/");

        //2. 创建连接，通过连接获取通道
        Connection connection = null;
        Channel channel = null;
        try{
            connection = factory.newConnection();
            channel = connection.createChannel();


            //3. 消费消息
            channel.basicQos(1);//一次只分发一条消息
            Channel finalChannel = channel;
            channel.basicConsume("queue7", false, new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
                    String messageBody = new String(message.getBody(), "utf-8");
                    System.out.println("work1 接收到消息：" + messageBody);
                    finalChannel.basicAck(message.getEnvelope().getDeliveryTag(), false);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            },new CancelCallback() {
                @Override
                public void handle(String consumerTag) throws IOException {
                    System.out.println("work1 消费者取消消费");
                }
            });

            System.in.read();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        }finally {
            //4. 关闭资源
            if (channel != null && channel.isOpen()){
                try {
                    channel.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (TimeoutException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null && connection.isOpen()){
                try {
                    channel.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (TimeoutException e) {
                    throw new RuntimeException(e);
                }
            }



        }
    }
}
